package edu.msse.signup.domain;

import java.util.List;


import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.mail.Multipart;

import org.apache.commons.mail.SimpleEmail;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;

public class UserFactory {
	static EntityManagerFactory emf =
        Persistence.createEntityManagerFactory("pu");
    public HtmlEmail mailSender;
	
	@SuppressWarnings("unchecked")
	public Users createUser(String name, String emailAddress, String phoneNumber, String password ) throws Exception
	{
		
		EntityManager jpa = emf.createEntityManager();
		List<Users> a=jpa.createQuery("from Users b where b.emailAddress=?").setParameter(1, emailAddress).getResultList();
	    if (a.size()>0)
	    {
	    	throw new Exception("User already exists");
	    	
	    }
	    
	    Users u=new Users(emailAddress,name,phoneNumber,password);
        EntityTransaction tx = jpa.getTransaction();
        try {
            tx.begin();
            jpa.persist(u);
            tx.commit();
        } catch (Exception x) {
        	x.printStackTrace();
        	tx.rollback();
            return null;
        }

        try{
            mailSender.setFrom("webmaster@volunteer.com","Volunteer Coordinators");
            mailSender.addTo(u.getEmailAddress(), u.getName());
            mailSender.setSubject("Volunteer Account Activation");
            mailSender.setHtmlMsg("Thank you for registering for the Volunteer Sign Up Service! <br />" +
                    "Click <a href=\"http://localhost:8080/faces/activate?email="+u.getEmailAddress()+"&key="+u.getRandomNumber()+
                    "\">here</a> to activate your account. <br /> If the above link does not work, try copying and pasting the following url into your browser: <br/>" +
                    "http://localhost:8080/faces/activate?email="+u.getEmailAddress()+"&key="+u.getRandomNumber());
            mailSender.send();

        }catch(Exception e){
            e.printStackTrace();
        }


       	System.out.println("User created. ID"+ u.getUserId());
       	return u;
	}

	public HtmlEmail getMailSender() {
		return mailSender;
	}

	public void setMailSender(HtmlEmail mailer) {
		this.mailSender = mailer;
	}
	
	

}
